<template>
  <div class="page-container relative tss">
    <BaseCollapse class="" title="基础信息">
      <DynamicForm :config="basicConfig" :questions="basicQuestions" ref="baseFrom" />
    </BaseCollapse>
    <BaseCollapse title="生效文件">
      <ViewTable></ViewTable>
    </BaseCollapse>
    <BaseCollapse title="培训安排">
      <DynamicForm :config="arrangeConfig" :questions="arrangeQuestions" ref="arrangeFrom" />
    </BaseCollapse>
    <BaseCollapse class="location" v-if="['TRACON', 'EFFCON', 'VIEW'].includes(state.showType)" title="培训总结">
      <DynamicForm :config="summaryConfig" :questions="summaryQuestions" ref="summaryFrom" />
      <span class="space-x-2 download">
        <a href="#" v-if="['EFFCON', 'VIEW'].includes(state.showType) && state.downLoadFlag" @click.prevent="handleDown">下载</a>
      </span>
    </BaseCollapse>
    <!-- <BaseCollapse v-if="['EFFCON', 'VIEW'].includes(state.showType)" title="生效确认">
      <DynamicForm :config="confirmationConfig" :questions="confirmationQuestions" ref="confirmationFrom" />
    </BaseCollapse> -->

    <ApprovalDetail v-if="['VIEW', 'EFFCON'].includes(state.showType) && query.processInstanceId" :config="approvalConfig" @back="approvalGoBack"></ApprovalDetail>

    <div class="space-x-2 w-full text-center my-4 btn">
      <a-button v-if="!['EFFCON'].includes(state.showType)" @click="cancel">返回</a-button>
      <a-button v-if="['TRACON', 'TRAPRE', 'SIGN'].includes(state.showType)" type="primary" @click="submit(state.showType)">提交</a-button>
      <a-button v-if="['VIEW'].includes(state.showType) && [1].includes(state.status)" type="primary" @click="handleEdit">编辑</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import ViewTable from './component/viewTable.vue';
import { HOST } from '@/config';
import { useUserStoreWithOut } from '@/store/modules/user';
import { computed, getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import HomeService from './index.service';
import BaseCollapse from '@/components/common/BaseCollapse/index.vue';
import AuditRecord from '@/components/common/AuditRecord/index.vue';
import ApprovalDetail from '@/components/approval-details/index.vue';
import { useRoute, useRouter } from 'vue-router';
import { Modal, message } from 'ant-design-vue';
import { Api, fileGet, fileAuto, trainingPrequalification, takeEffectConfirmation, trainingConfirmation, treeDataSubject } from '@/config/api/documentValidation';
import { DynamicForm } from '@/components/public-template';
import { formInfoStore } from '@/store/modules/form';
import { throttle } from 'xe-utils';

const { query } = useRoute();
const router = useRouter();
const route = useRoute();
const fileData: any = ref({});
const formStore = formInfoStore();
const state = reactive({
  showType: '', // View TRAPRE TRACON EFFCON
  status: null,
  id: null, // 培训总结附件Id
  downLoadFlag: false // 下载
});

const approvalConfig: any = ref({
  title: '审批流程',
  showBackBtn: true, //显示返回按钮
  showAgreeBtn: true, //显示同意按钮
  showGoBackBtn: true, // 显示退回按钮
  showRejectBtn: true // 显示拒绝按钮
});

const approvalGoBack = (cb: any) => {
  cb?.();
};

state.showType = route.query.showType as string;
const basicQuestions: any = reactive(HomeService.getQuestions());
const arrangeQuestions: any = reactive(HomeService.getArrangeQuestions(state.showType));
const summaryQuestions: any = reactive(
  HomeService.getSummaryQuestions(state.showType, (data) => {
    fileData.value = data[0];
  })
);
formStore.setQuestions(reactive(HomeService.getConfirmationQuestions(state.showType)));
const confirmationQuestions: any = computed(() => formStore.getQuestions);

const basicConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const arrangeConfig: any = {
  labelCol: 8,
  wrapperCol: 18,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const summaryConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 10,
  layout: 'vertical',
  cancelSave: true
};
const confirmationConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 8,
  layout: 'vertical',
  cancelSave: true
};
const baseFrom = ref(null); // 基础信息
const arrangeFrom = ref(null); // 培训安排信息
const summaryFrom = ref(null); // 培训总结
const confirmationFrom = ref(null); // 生效确认

onMounted(() => {
  if (['VIEW'].includes(state.showType)) {
    approvalConfig.value.showBackBtn = false;
    approvalConfig.value.showAgreeBtn = false;
    approvalConfig.value.showGoBackBtn = false;
    approvalConfig.value.showRejectBtn = false;
  }
  fileAuto().then((result) => {
    if (result.success) {
      // 基本信息
      const data = result.data;
      basicQuestions.forEach((item) => (item.value = data[item.key]));
    }
  });
  fileGet(route.query.id).then((result) => {
    if (result.success) {
      const data = result.data;
      state.status = data.status;
      state.id = data.attachment?.id;
      if (data.attachment) {
        state.downLoadFlag = true;
      }
      if (state.showType !== 'TRAPRE' && data.trainBeignDate && data.trainEndDate) {
        data.trainDate = `${data.trainBeignDate} ~ ${data.trainEndDate}`;
        treeDataSubject({ parentId: 0 }).then((result) => {
          if (result.success) {
            result.data.map((item) => {
              if (item.id === data.organizer) {
                data.organizer = item.nickName;
              }
            });
            data.organizer = arrangeQuestions.forEach((item) => (item.value = data[item.key]));
          }
        });
      }
      if (['EFFCON', 'VIEW'].includes(state.showType)) {
        summaryQuestions.forEach((item) => (item.value = data[item.key]));
      }
      if (['VIEW'].includes(state.showType)) {
        confirmationQuestions.value.forEach((item) => (item.value = data[item.key]));
      }
    }
  });
});

// 提交操作
const submit = throttle(async function (showType) {
  Modal.confirm({
    title: '是否确定提交',
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      if (showType == 'TRAPRE') {
        let isError;
        await arrangeFrom.value.isValidateFields().catch((error) => {
          isError = true;
          console.log(error);
        });
        const arrangeData = arrangeFrom.value.getDataFrom();
        if (arrangeData.trainDate.length == 2) {
          arrangeData.trainBeignDate = arrangeData.trainDate[0];
          arrangeData.trainEndDate = arrangeData.trainDate[1];
          Reflect.deleteProperty(arrangeData, 'trainDate');
        }
        if (isError) return;
        let params = Object.assign({ id: route.query.id }, arrangeData);
        trainingPrequalification(params).then((result) => {
          if (result.success) {
            message.success('提交成功');
            router.go(-1);
          }
        });
      } else if (showType == 'TRACON') {
        let isError;
        await summaryFrom.value.isValidateFields().catch((error) => {
          isError = true;
          console.log(error);
        });
        const summaryData = summaryFrom.value.getDataFrom();
        const attachment = {
          trainProcessId: route.query.id,
          id: fileData.value.id,
          code: fileData.value.storeUrl,
          type: fileData.value.name,
          size: fileData.value.size,
          suffix: fileData.value.size
        };
        if (isError) return;

        let params = Object.assign({ id: route.query.id }, { attachment: attachment }, { trainSummary: summaryData.trainSummary });
        takeEffectConfirmation(params).then((result) => {
          if (result.success) {
            message.success('提交成功');
            router.go(-1);
          }
        });
      } else if (showType == 'EFFCON') {
        const confirmationData = confirmationFrom.value.getDataFrom();
        let params = Object.assign({ id: route.query.id }, confirmationData);
        trainingConfirmation(params).then((result) => {
          if (result.success) {
            message.success('提交成功');
            router.go(-1);
          }
        });
      }
    }
  });
}, 1000);

// 下载
const accessToken = useUserStoreWithOut().getToken;
function handleDown() {
  const url = `${Api.fileTemplateDownload}/${state.id}`;
  const xhr = new XMLHttpRequest();
  xhr.open('GET', `${HOST}${url}`, true);
  xhr.setRequestHeader('token', accessToken);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    if (this.status == 200) {
      const blob = new Blob([this.response], { type: 'contentType' });
      const contentDisposition = xhr.getResponseHeader('content-disposition');
      let filename = contentDisposition.substring(contentDisposition.indexOf('filename')).replace(/"/gi, '');
      filename = window.decodeURIComponent(filename.substring(filename.indexOf('=') + 1));
      const a = document.createElement('a');
      a.href = window.URL.createObjectURL(blob);
      a.download = filename;
      a.click();
      window.URL.revokeObjectURL(url);
    }
  };
  xhr.send();
}
function cancel() {
  router.go(-1);
}
function handleEdit() {
  router
    .replace({
      name: 'documentValidationDetailFile',
      query: {
        id: route.query.id,
        showType: 'TRAPRE'
      }
    })
    .then(() => {
      router.go(0);
    });
}
</script>

<style lang="less" scoped>
.tss {
  .location {
    position: relative;
  }

  > .w-full {
    margin-bottom: 50px;
  }
}
.download {
  position: absolute;
  left: 58%;
  top: 64%;
}
</style>
